package cz.muni.fi.pa165.musiclibrary.impl.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Nonnull;

import org.apache.commons.lang3.Validate;
import org.joda.time.LocalDate;
import org.springframework.transaction.annotation.Transactional;

import cz.muni.fi.pa165.musiclibrary.impl.database.dao.IAlbumDAO;
import cz.muni.fi.pa165.musiclibrary.impl.database.entity.IAlbum;
import cz.muni.fi.pa165.musiclibrary.api.service.IAlbumService;
import cz.muni.fi.pa165.musiclibrary.api.service.dto.IAlbumDTO;
import cz.muni.fi.pa165.musiclibrary.impl.service.dto.translator.AlbumDTOTranslator;

/**
 * Service implementation for working with albums.
 * 
 * @author Maros Kucbel
 * @date 2012-10-28T20:15:39+0100
 */
@Transactional
public final class AlbumService implements IAlbumService {

    private IAlbumDAO albumDao;
    
    public AlbumService(final IAlbumDAO albumDao) {
        this.albumDao = albumDao;
    }
    
    @Override
    public void create(final IAlbumDTO album, String userName) {
        Validate.isTrue(album != null, "Album should not be null.");
        final IAlbum entity = AlbumDTOTranslator.translateFromDTO(album);
        this.albumDao.create(entity);
    }

    @Override
    public void update(final IAlbumDTO album, String userName) {
        Validate.isTrue(album != null, "Album should not be null.");
        final IAlbum entity = AlbumDTOTranslator.translateFromDTO(album);
        this.albumDao.update(entity);
    }

    @Override
    public void delete(final IAlbumDTO album, String userName) {
        Validate.isTrue(album != null, "Album should not be null.");
        final IAlbum entity = AlbumDTOTranslator.translateFromDTO(album);
        this.albumDao.delete(entity);
    }

    @Override
    public IAlbumDTO getById(final Long id) {
        Validate.isTrue(id != null, "Identifier should not be null.");
        final IAlbum entity = this.albumDao.getById(id);
        return AlbumDTOTranslator.translateToDTO(entity);
    }

    @Override
    public List<IAlbumDTO> getAll() {
        final List<IAlbum> albums = this.albumDao.getAll();
        return this.translateList(albums);
    }

    @Override
    public List<IAlbumDTO> getByTitle(final String title) {
        Validate.isTrue(title != null, "Search string should not be null.");
        final List<IAlbum> albums = this.albumDao.getByTitle(title);
        return this.translateList(albums);
    }

    /**
     * Translates a list of entity objects to DTO objects.
     * @param albums Albums to translate.
     * @return Translated DTO objects.
     */
    @Nonnull
    private List<IAlbumDTO> translateList(final List<IAlbum> albums) {
        final List<IAlbumDTO> dtos = new ArrayList<IAlbumDTO>(albums.size());
        for (final IAlbum album : albums) {
            final IAlbumDTO dto = AlbumDTOTranslator.translateToDTO(album);
            dtos.add(dto);
        }
        return dtos;
    }
}